<template>
	<view class="content">
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator url="/pages/account/account" open-type="switchTab" class="back-button">
					<view class="nav-back-content">
						<u-icon color="#1e88e5" name="arrow-left"></u-icon>
						<view class="nav-title">银行流水</view>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<view class="filter-wrapper">
			<view class="type-filter-container">
				<view class="filter-left">
					<view class="type-filter-item" @click="showIncomeTypePicker = true">
						<text>{{ selectedIncomeTypeText || '收支类型' }}</text>
						<u-icon name="arrow-down" size="14" color="#4188EF"></u-icon>
					</view>
					<view class="type-filter-item" @click="showTradeTypePicker = true">
						<text>{{ selectedTradeTypeText || '交易类型' }}</text>
						<u-icon name="arrow-down" size="14" color="#4188EF"></u-icon>
					</view>
				</view>

				<view class="sync-button" @click="syncBankFlow">
					<u-icon name="reload" size="16" color="#4188EF" class="sync-icon"></u-icon>
					<text>同步银行流水</text>
				</view>
			</view>

			<view class="date-stat-container">
				<view class="date-filter" @click="showDatePicker = true">
					<text>{{ selectedDate || '选择月份' }}</text> <!-- 默认显示提示文本 -->
					<u-icon name="arrow-down" size="14" color="#4188EF"></u-icon>
				</view>
				<view class="expense-income-stat">
					<text class="expense">支出{{ totalExpense.toFixed(2) }}</text>
					<text class="income">收入{{ totalIncome.toFixed(2) }}</text>
				</view>
			</view>
		</view>

		<view class="balance-container">
			<view class="balance-item">
				<text class="balance-label">余额</text>
				<text class="balance-value">{{ currentBalance.toFixed(2) }}</text>
			</view>
			<view class="balance-item">
				<text class="balance-label">初期余额</text>
				<text class="balance-value">{{ initialBalance.toFixed(2) }}</text>
			</view>
		</view>

		<view class="transaction-container">
			<view class="transaction-list">
				<view v-if="transactions.length === 0 && !isLoading" class="no-data">
					<text>暂无交易记录</text>
				</view>
				<view v-else-if="filteredTransactions.length === 0 && !isLoading" class="no-data">
					<text>暂无匹配的交易记录</text>
				</view>

				<view class="transaction-item" v-for="(item, index) in filteredTransactions" :key="index">
					<view class="transaction-top">
						<text class="trade-type">{{ item.tradeTypeName }}</text>
						<text class="amount"
							:class="item.type">{{ item.type === 'income' ? '+' : '-' }}{{ item.amount.toFixed(2) }}</text>
					</view>
					<view class="transaction-bottom">
						<text class="trade-date">{{ formatDate(item.tradeDate) }}</text>
						<text class="trade-type-label">交易类型：{{ item.tradeTypeName }}</text>
					</view>
				</view>
			</view>

			<!-- 上拉加载提示（新增） -->
			<view v-if="isLoading" class="loading-state">
				<u-loading-icon color="#4188EF" size="28"></u-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
			<view v-if="!isLoading && hasMore && transactions.length > 0" class="load-more" @click="loadMore">
				<text class="load-more-text">点击加载更多</text>
			</view>
			<view v-if="!hasMore && transactions.length > 0" class="no-more">
				<text class="no-more-text">暂无更多数据</text>
			</view>
		</view>

		<view class="fixed-bottom-buttons">
			<view class="btn-container">
				<view class="btn save-btn" @click="showAddFlowDialog = true">
					添加流水
				</view>
			</view>
		</view>
		<!-- 添加流水弹窗 -->
		<u-popup :show="showAddFlowDialog" @close="handleDialogClose" @open="handleDialogOpen" mode="center" :round="16"
			:closeOnClickOverlay="false">
			<view class="popup-content">
				<view class="popup-title">添加财务流水</view>

				<view class="add-flow-form">
					<!-- 交易类型选择 -->
					<view class="form-item">
						<text class="form-label">交易类型</text>
						<view class="form-control" @click="showAddTradeTypePicker = true">
							<text>{{ newFlow.tradeTypeName || '请选择交易类型' }}</text>
							<u-icon name="arrow-right" size="18" color="#999"></u-icon>
						</view>
					</view>

					<!-- 收支类型选择 -->
					<view class="form-item">
						<text class="form-label">收支类型</text>
						<view class="form-control" @click="showAddIncomeTypePicker = true">
							<text>{{ newFlow.incomeType === 1 ? '收入' : newFlow.incomeType === 0 ? '支出' : '请选择收支类型' }}</text>
							<u-icon name="arrow-right" size="18" color="#999"></u-icon>
						</view>
					</view>

					<!-- 金额输入 -->
					<view class="form-item">
						<text class="form-label">金额</text>
						<view class="form-control">
							<input type="number" v-model="newFlow.amount" placeholder="请输入金额" class="input-control"
								step="0.01" min="0.01" />
						</view>
					</view>

					<!-- 日期选择 -->
					<view class="form-item">
						<text class="form-label">日期</text>
						<view class="form-control" @click="showAddDatePicker = true">
							<text>{{ newFlow.tradeDate || '请选择日期' }}</text>
							<u-icon name="arrow-right" size="18" color="#999"></u-icon>
						</view>
					</view>

					<!-- 备注 -->
					<view class="form-item">
						<text class="form-label">备注</text>
						<view class="form-control">
							<input type="text" v-model="newFlow.remark" placeholder="请输入备注信息" class="input-control" />
						</view>
					</view>
				</view>

				<view class="popup-buttons">
					<view class="cancel-btn" @click="showAddFlowDialog = false">取消</view>
					<view class="confirm-btn" @click="confirmAddFlow">确定</view>
				</view>
			</view>
		</u-popup>

		<!-- 筛选器组件 -->
		<u-picker :show="showIncomeTypePicker" :columns="incomeTypeColumns" keyName="label" @confirm="confirmIncomeType"
			@cancel="showIncomeTypePicker = false"></u-picker>

		<u-picker :show="showTradeTypePicker" :columns="tradeTypeColumns" keyName="label" @confirm="confirmTradeType"
			@cancel="showTradeTypePicker = false"></u-picker>

		<!-- 添加流水弹窗中的选择器 -->
		<u-picker :show="showAddTradeTypePicker" :columns="tradeTypeColumns" keyName="label"
			@confirm="confirmAddTradeType" @cancel="showAddTradeTypePicker = false"></u-picker>

		<u-picker :show="showAddIncomeTypePicker" :columns="incomeTypeColumns" keyName="label"
			@confirm="confirmAddIncomeType" @cancel="showAddIncomeTypePicker = false"></u-picker>

		<!-- 时间选择器 -->
		<u-datetime-picker :show="showDatePicker" v-model="value1" mode="year-month" @confirm="handleDateConfirm"
			@cancel="showDatePicker = false"></u-datetime-picker>

		<u-datetime-picker :show="showAddDatePicker" v-model="addDateValue" mode="datetime"
			@confirm="handleAddDateConfirm" @cancel="showAddDatePicker = false"></u-datetime-picker>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				// 公司信息
				companyInfo: uni.getStorageSync('companyInfo') || {},
				http: uni.$u.http, // 统一请求实例
				// 筛选器状态 - 中文显示文本变量
				showIncomeTypePicker: false,
				showTradeTypePicker: false,
				showDatePicker: false,
				value1: new Date(), // 初始化为当前日期对象
				selectedIncomeType: 'all', // 默认选中全部
				selectedIncomeTypeText: '收支类型', // 默认显示文本
				selectedTradeType: 'all', // 默认选中全部
				selectedTradeTypeText: '交易类型', // 默认显示文本
				selectedDate: '', // 初始化为空，后续在created中设置当前月

				// 添加流水弹窗相关
				showAddFlowDialog: false,
				showAddTradeTypePicker: false,
				showAddIncomeTypePicker: false,
				showAddDatePicker: false,
				addDateValue: new Date(),
				newFlow: {
					tradeTypeId: '',
					tradeTypeName: '',
					incomeType: '',
					amount: '',
					tradeDate: '',
					remark: '',
					syncSource: 'manual' // 默认手动添加
				},

				// 筛选选项（收支类型与接口保持一致：1=收入，0=支出）
				incomeTypeColumns: [
					[{
							label: '全部',
							value: 'all'
						},
						{
							label: '收入',
							value: 1
						},
						{
							label: '支出',
							value: 0
						}
					]
				],
				tradeTypeColumns: [
					[{
						label: '全部',
						value: 'all'
					}] // 默认添加全部选项
				],

				// 余额信息
				initialBalance: 0,
				currentBalance: 0,
				totalIncome: 0,
				totalExpense: 0,

				// 交易记录数据
				transactions: [],
				// 缓存交易类型列表（用于匹配名称）
				tradeTypeList: [],

				// 分页相关参数（新增）
				pageNumber: 1, // 当前页码
				pageSize: 6, // 每页条数
				total: 0, // 总记录数
				isLoading: false, // 是否正在加载
				hasMore: true // 是否还有更多数据
			}
		},
		computed: {
			companyId() {
				return this.companyInfo.id || '';
			},
			filteredTransactions() {
				// 深拷贝避免影响原数据
				let result = [...this.transactions];

				console.log('筛选条件：', {
					selectedIncomeType: this.selectedIncomeType,
					selectedTradeType: this.selectedTradeType,
					selectedDate: this.selectedDate
				});

				// 收支类型筛选
				if (this.selectedIncomeType !== 'all') {
					const incomeType = Number(this.selectedIncomeType);
					result = result.filter(item => {
						const itemType = Number(item.incomeType);
						const isMatch = itemType === incomeType;
						return isMatch;
					});
				}

				// 交易类型筛选
				if (this.selectedTradeType !== 'all') {
					result = result.filter(item => {
						const isMatch = item.tradeTypeId === this.selectedTradeType;
						return isMatch;
					});
				}

				// 日期筛选（selectedDate为空时不筛选）
				if (this.selectedDate) {
					result = result.filter(item => {
						const itemMonth = this.formatDate(item.tradeDate, 'yyyy-MM');
						const isMatch = itemMonth === this.selectedDate;
						console.log(
							`日期匹配：item=${item.tradeDate} → ${itemMonth}, 筛选条件=${this.selectedDate}, 结果=${isMatch}`
						);
						return isMatch;
					});
				}

				console.log('筛选后记录数：', result.length);
				return result;
			}
		},
		created() {
			// 1. 初始化默认当前月
			this.setDefaultCurrentMonth();
			// 2. 初始化数据（带当前月筛选）
			this.initData();
		},
		// 上拉触底事件（新增）
		onReachBottom() {
			if (this.hasMore && !this.isLoading) {
				this.loadMore();
			}
		},
		methods: {
			// 初始化默认当前月（关键：设置selectedDate为当前年月）
			setDefaultCurrentMonth() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0');
				this.selectedDate = `${year}-${month}`; // 格式：yyyy-MM
			},

			// 初始化数据
			async initData() {
				if (!this.companyId) {
					uni.showToast({
						title: '请先选择公司',
						icon: 'none'
					});
					return;
				}

				try {
					// 重置分页参数（新增）
					this.pageNumber = 1;
					this.total = 0;
					this.hasMore = true;
					this.transactions = [];

					// 顺序加载数据
					await this.loadTradeTypes();
					await this.loadBankFlows(); // 此时已携带当前月参数
					await this.loadBalanceInfo();

					// 计算当前余额
					this.currentBalance = this.initialBalance + this.totalIncome - this.totalExpense;

					console.log('交易记录:', this.transactions);
					console.log('初始筛选后记录:', this.filteredTransactions);
				} catch (error) {
					console.error('初始化数据失败:', error);
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				}
			},

			// 加载交易类型
			async loadTradeTypes() {
				try {
					const res = await this.http.get('/VipTradeType/list', {
						params: {
							companyId: this.companyId,
							pageSize: 100
						}
					});

					if (res.code === 200 && res.data && res.data.data) {
						// 缓存交易类型列表（过滤掉"全部"选项）
						this.tradeTypeList = res.data.data.filter(item => item.tradeName !== '全部');

						// 转换为选择器格式（保留"全部"选项）
						const tradeTypes = [{
							label: '全部',
							value: 'all'
						}];

						this.tradeTypeList.forEach(item => {
							tradeTypes.push({
								label: item.tradeName,
								value: item.id // 确保value是字符串（与接口返回一致）
							});
						});

						this.tradeTypeColumns = [tradeTypes];
						console.log('交易类型选择器:', tradeTypes);
					}
				} catch (error) {
					console.error('加载交易类型失败:', error);
					throw error;
				}
			},

			// 加载银行流水（修改：添加分页逻辑）
			async loadBankFlows() {
				if (this.isLoading) return;

				this.isLoading = true;
				try {
					const params = {
						companyId: this.companyId,
						pageNumber: this.pageNumber, // 新增分页参数
						pageSize: this.pageSize, // 新增分页参数
						tradeDate: this.selectedDate, // 传递当前选中的年月（yyyy-MM）
						// 传递筛选条件（新增）
						incomeType: this.selectedIncomeType !== 'all' ? this.selectedIncomeType : '',
						tradeTypeId: this.selectedTradeType !== 'all' ? this.selectedTradeType : ''
					};
					const res = await this.http.get('/VipBankFlow/list', {
						params
					});

					if (res.code === 200 && res.data) {
						const {
							data,
							total
						} = res.data;
						this.total = total; // 保存总记录数

						// 转换数据格式（保持原有格式不变）
						const formattedData = data.map(item => {
							const tradeType = this.tradeTypeList.find(t => t.id === item.tradeTypeId) || {};
							return {
								id: item.id,
								tradeTypeId: item.tradeTypeId, // 保持字符串类型
								tradeTypeName: tradeType.tradeName || '未知类型',
								incomeType: item.incomeType, // 接口返回数字，保持原样
								type: item.incomeType === 1 ? 'income' : 'expense',
								amount: Number(item.amount) || 0,
								tradeDate: item.tradeDate, // 保留后端返回的原始日期字符串
								remark: item.remark,
								syncSource: item.syncSource
							};
						});

						// 分页加载：第一页替换，后续页追加（新增逻辑）
						if (this.pageNumber === 1) {
							this.transactions = formattedData;
						} else {
							this.transactions = [...this.transactions, ...formattedData];
						}

						// 判断是否还有更多数据（新增逻辑）
						this.hasMore = this.transactions.length < this.total;

						// 计算总收入和总支出
						this.calculateTotalAmounts();
						console.log(
							`加载流水数: ${formattedData.length}，累计: ${this.transactions.length}，总条数: ${this.total}`);
					}
				} catch (error) {
					console.error('加载银行流水失败:', error);
					// 加载失败回滚页码（新增）
					if (this.pageNumber > 1) {
						this.pageNumber--;
					}
					throw error;
				} finally {
					this.isLoading = false; // 结束加载状态（新增）
				}
			},

			// 加载更多（新增方法）
			async loadMore() {
				if (this.isLoading || !this.hasMore) return;

				this.pageNumber++;
				await this.loadBankFlows();
			},

			// 加载余额信息
			async loadBalanceInfo() {
				try {
					const res = await this.http.get('/VipBalanceConfig/list', {
						params: {
							companyId: this.companyId,
							pageSize: 1
						}
					});

					if (res.code === 200 && res.data && res.data.data && res.data.data.length > 0) {
						const balanceInfo = res.data.data[0];
						this.initialBalance = Number(balanceInfo.initialBalance) || 0;
					}
				} catch (error) {
					console.error('加载余额信息失败:', error);
					throw error;
				}
			},

			// 计算总收入和总支出
			calculateTotalAmounts() {
				this.totalIncome = this.transactions
					.filter(item => Number(item.incomeType) === 1)
					.reduce((sum, item) => sum + Number(item.amount), 0);

				this.totalExpense = this.transactions
					.filter(item => Number(item.incomeType) === 0)
					.reduce((sum, item) => sum + Number(item.amount), 0);
			},

			// 格式化日期（关键：iOS兼容处理）
			formatDate(dateString, format = 'yyyy-MM-dd HH:mm') {
				if (!dateString) return '';

				let date;
				if (typeof dateString === 'string') {
					dateString = dateString.trim();
					// iOS兼容：处理两种不支持的格式
					// 1. 把 "yyyy-MM-dd HH:mm:ss" 转为 "yyyy/MM/dd HH:mm:ss"（iOS支持）
					// 2. 保留 ISO格式 "yyyy-MM-ddTHH:mm:ss"（iOS原生支持）
					if (dateString.includes(' ') && dateString.includes('-')) {
						dateString = dateString.replace(/-/g, '/'); // 替换分隔符
					}
					date = new Date(dateString);
				} else if (dateString instanceof Date) {
					date = dateString;
				} else {
					return '';
				}

				// 容错处理：解析失败时返回原始字符串
				if (isNaN(date.getTime())) {
					console.warn('日期解析失败:', dateString);
					return dateString;
				}

				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');

				// 按传入格式返回（支持 yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH:mm 等）
				return format.replace('yyyy', year)
					.replace('MM', month)
					.replace('dd', day)
					.replace('HH', hour)
					.replace('mm', minute);
			},

			// 筛选器确认方法（修改：筛选后重置分页并重新加载）
			confirmIncomeType(e) {
				this.selectedIncomeType = e.value[0].value;
				this.selectedIncomeTypeText = e.value[0].label;
				this.showIncomeTypePicker = false;
				// 筛选条件变化，重置分页并重新加载
				this.pageNumber = 1;
				this.hasMore = true;
				this.loadBankFlows();
			},

			confirmTradeType(e) {
				this.selectedTradeType = e.value[0].value;
				this.selectedTradeTypeText = e.value[0].label;
				this.showTradeTypePicker = false;
				// 筛选条件变化，重置分页并重新加载
				this.pageNumber = 1;
				this.hasMore = true;
				this.loadBankFlows();
			},

			// 时间选择器确认（关键：处理ISO格式字符串 + 切换月份后重新加载数据）
			handleDateConfirm(e) {
				console.log('时间选择器返回值:', e);
				let year, month;

				// 处理三种返回格式：数组、Date对象、ISO格式字符串对象
				if (Array.isArray(e)) {
					year = e[0];
					month = e[1].toString().padStart(2, '0');
				} else if (e instanceof Date) {
					year = e.getFullYear();
					month = (e.getMonth() + 1).toString().padStart(2, '0');
				} else if (typeof e === 'object' && e.value) {
					// 处理 u-datetime-picker 返回的 ISO 格式（如：2025-11-24T08:48:18.513Z）
					const isoDate = new Date(e.value);
					year = isoDate.getFullYear();
					month = (isoDate.getMonth() + 1).toString().padStart(2, '0');
				}

				// 更新选中月份并重新加载流水
				if (year && month) {
					this.selectedDate = `${year}-${month}`;
					// 切换月份，重置分页并重新加载
					this.pageNumber = 1;
					this.hasMore = true;
					this.loadBankFlows(); // 切换月份后重新请求数据
				}
				this.showDatePicker = false;
			},

			// 添加流水日期选择（关键：生成iOS兼容的日期格式）
			// 添加流水日期选择（兼容 u-datetime-picker 所有返回格式 + iOS 兼容）
			handleAddDateConfirm(e) {
				console.log('日期选择返回值:', e); // 方便调试，可保留
				let date = null;

				// 兼容 4 种常见返回格式
				if (typeof e === 'string') {
					// 格式1：直接返回字符串（如 "2025-11-24 17:30" 或 "2025/11/24 17:30"）
					date = new Date(e);
				} else if (e instanceof Date) {
					// 格式2：返回 Date 对象
					date = e;
				} else if (Array.isArray(e)) {
					// 格式3：返回数组（如 [2025, 11, 24, 17, 30]）
					const [year, month, day, hour, minute] = e;
					date = new Date(year, month - 1, day, hour, minute); // 月份需减1（JS月份0-11）
				} else if (typeof e === 'object' && e.value) {
					// 格式4：返回 ISO 格式对象（如 {value: "2025-11-24T08:48:18.513Z"}）
					date = new Date(e.value);
				}

				// 容错处理：若日期解析失败，提示用户
				if (!date || isNaN(date.getTime())) {
					uni.showToast({
						title: '日期选择失败，请重新选择',
						icon: 'none'
					});
					this.showAddDatePicker = false;
					return;
				}

				// 生成 iOS 兼容的日期格式：yyyy/MM/dd HH:mm:ss（后端已改为 String 类型，兼容存储）
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份补0
				const day = date.getDate().toString().padStart(2, '0'); // 日期补0
				const hour = date.getHours().toString().padStart(2, '0'); // 小时补0
				const minute = date.getMinutes().toString().padStart(2, '0'); // 分钟补0
				const dateStr = `${year}/${month}/${day} ${hour}:${minute}:00`;

				// 赋值并关闭选择器（关键：让页面实时显示选中的日期）
				this.newFlow.tradeDate = dateStr;
				this.showAddDatePicker = false;
			},

			// 同步银行流水方法
			async syncBankFlow() {
				uni.showToast({
					title: '同步中...',
					icon: 'loading',
					duration: 1500
				});

				try {
					const res = await this.http.post('/VipBankFlow/sync', {
						companyId: this.companyId
					});

					if (res.code === 200) {
						uni.showToast({
							title: '同步成功',
							icon: 'success'
						});
						setTimeout(() => {
							this.initData(); // 同步后重新初始化数据（会重置分页）
						}, 500);
					} else {
						uni.showToast({
							title: res.msg || '同步失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('同步银行流水失败:', error);
					uni.showToast({
						title: '同步失败',
						icon: 'none'
					});
				}
			},

			// 添加流水相关方法
			confirmAddTradeType(e) {
				if (e.value[0].value !== 'all') {
					this.newFlow.tradeTypeId = e.value[0].value;
					this.newFlow.tradeTypeName = e.value[0].label;
				}
				this.showAddTradeTypePicker = false;
			},

			confirmAddIncomeType(e) {
				if (e.value[0].value !== 'all') {
					this.newFlow.incomeType = e.value[0].value;
				}
				this.showAddIncomeTypePicker = false;
			},

			handleDialogClose() {
				this.showAddFlowDialog = false;
				this.resetForm();
			},

			handleDialogOpen() {
				console.log('弹窗已打开');
			},

			resetForm() {
				this.newFlow = {
					tradeTypeId: '',
					tradeTypeName: '',
					incomeType: '',
					amount: '',
					tradeDate: '',
					remark: '',
					syncSource: 'manual'
				};
			},

			// 确认添加流水
			async confirmAddFlow() {
				if (!this.newFlow.tradeTypeId) {
					uni.showToast({
						title: '请选择交易类型',
						icon: 'none'
					});
					return;
				}
				if (this.newFlow.incomeType === '' || this.newFlow.incomeType === null) {
					uni.showToast({
						title: '请选择收支类型',
						icon: 'none'
					});
					return;
				}
				if (!this.newFlow.amount || isNaN(parseFloat(this.newFlow.amount)) || parseFloat(this.newFlow
						.amount) <= 0) {
					uni.showToast({
						title: '请输入有效的金额',
						icon: 'none'
					});
					return;
				}
				if (!this.newFlow.tradeDate) {
					uni.showToast({
						title: '请选择日期',
						icon: 'none'
					});
					return;
				}

				try {
					const submitData = {
						companyId: this.companyId,
						incomeType: Number(this.newFlow.incomeType),
						tradeTypeId: this.newFlow.tradeTypeId,
						amount: parseFloat(this.newFlow.amount),
						tradeDate: this.newFlow.tradeDate, // 已是iOS兼容格式
						syncSource: this.newFlow.syncSource,
						remark: this.newFlow.remark,
						reserve1: '',
						reserve2: ''
					};

					const res = await this.http.post('/VipBankFlow', submitData);

					if (res.code === 200) {
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						});
						this.showAddFlowDialog = false;
						this.resetForm();
						this.initData(); // 添加后重新初始化数据（会重置分页）
					} else {
						uni.showToast({
							title: res.msg || '添加失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('添加流水失败:', error);
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	// 保持原有样式不变
	.content {
		background: #fff;
		min-height: 100vh;
		padding-bottom: 160rpx;

		.navbar-left {
			.nav-back-content {
				display: flex;
				align-items: center;

				.nav-title {
					font-size: 34rpx;
					font-weight: bold;
					color: #1e88e5;
					margin-left: 16rpx;
				}
			}
		}

		.filter-wrapper {
			background: #fff;
			padding: 20rpx 32rpx;

			.type-filter-container {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				flex-wrap: nowrap;

				.filter-left {
					display: flex;
					gap: 20rpx;
				}

				.type-filter-item {
					display: flex;
					align-items: center;
					padding: 16rpx 30rpx;
					background: #f0f7ff;
					border-radius: 24rpx;
					font-size: 28rpx;
					color: #4188EF;
					border: none;
					cursor: pointer;

					u-icon {
						margin-left: 8rpx;
					}
				}

				.sync-button {
					display: flex;
					align-items: center;
					padding: 16rpx 30rpx;
					background: #f0f7ff;
					border-radius: 24rpx;
					font-size: 28rpx;
					color: #4188EF;
					border: none;
					cursor: pointer;

					.sync-icon {
						margin-right: 8rpx;
					}
				}
			}

			.date-stat-container {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.date-filter {
					display: flex;
					align-items: center;
					color: #333;
					font-size: 28rpx;
					cursor: pointer;

					u-icon {
						margin-left: 8rpx;
					}
				}

				.expense-income-stat {
					display: flex;
					gap: 30rpx;
					font-size: 28rpx;

					.expense {
						color: #ff4d4f;
					}

					.income {
						color: #52c41a;
					}
				}
			}
		}

		.balance-container {
			background: linear-gradient(135deg, #4188EF 0%, #1E88E5 100%);
			margin: 30rpx 32rpx;
			border-radius: 16rpx;
			padding: 36rpx 32rpx;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.balance-item {
				text-align: center;

				.balance-label {
					display: block;
					font-size: 28rpx;
					color: rgba(255, 255, 255, 0.85);
					margin-bottom: 10rpx;
				}

				.balance-value {
					display: block;
					font-size: 36rpx;
					font-weight: bold;
					color: #ffffff;
				}
			}
		}

		.transaction-container {
			padding: 0 32rpx;

			.transaction-list {
				.transaction-item {
					background: #f6f9fe;
					border-radius: 16rpx;
					padding: 24rpx 30rpx;
					margin-bottom: 16rpx;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

					.transaction-top {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 16rpx;

						.trade-type {
							font-size: 32rpx;
							color: #000;
						}

						.amount {
							font-size: 32rpx;

							&.income {
								color: #52c41a;
							}

							&.expense {
								color: #ff4d4f;
							}
						}
					}

					.transaction-bottom {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.trade-date {
							font-size: 26rpx;
							color: #999;
						}

						.trade-type-label {
							font-size: 26rpx;
							color: #999;
						}
					}
				}
			}

			// 上拉加载相关样式（新增）
			.loading-state {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 30rpx 0;
				color: #999;
				font-size: 28rpx;
				gap: 10rpx;
			}

			.load-more {
				text-align: center;
				padding: 30rpx 0;
				color: #4188EF;
				font-size: 28rpx;
				cursor: pointer;
			}

			.no-more {
				text-align: center;
				padding: 30rpx 0;
				color: #999;
				font-size: 28rpx;
			}
		}

		.no-data {
			text-align: center;
			padding: 60rpx 0;
			color: #999;
			font-size: 28rpx;
		}

		.fixed-bottom-buttons {
			z-index: 9;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #ffffff;
			padding: 16px;
			box-sizing: border-box;
			max-width: 750rpx;
			margin: 0 auto;
		}

		.btn-container {
			width: 100%;
		}

		.btn {
			width: 100%;
			height: 48px;
			line-height: 48px;
			text-align: center;
			border-radius: 8px;
			font-size: 16px;
			font-weight: 500;
			transition: all 0.2s ease;
		}

		.save-btn {
			background-color: #409EFF;
			color: #ffffff;
			border: none;
		}

		.save-btn:active {
			background-color: #337ecc;
		}

		.popup-content {
			width: 650rpx;
			background-color: #fff;
			border-radius: 16rpx;
			overflow: hidden;

			.popup-title {
				font-size: 34rpx;
				font-weight: bold;
				color: #333;
				text-align: center;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #f5f5f5;
			}

			.add-flow-form {
				padding: 20rpx 30rpx;

				.form-item {
					display: flex;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #f5f5f5;

					&:last-child {
						border-bottom: none;
					}

					.form-label {
						width: 160rpx;
						font-size: 28rpx;
						color: #333;
					}

					.form-control {
						flex: 1;
						display: flex;
						justify-content: space-between;
						align-items: center;
						font-size: 28rpx;
						color: #666;
					}

					.input-control {
						width: 100%;
						font-size: 28rpx;
						color: #333;
						padding: 0;
						margin: 0;
						border: none;
						outline: none;
					}
				}
			}

			.popup-buttons {
				display: flex;
				height: 90rpx;
				border-top: 1rpx solid #f5f5f5;

				.cancel-btn,
				.confirm-btn {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 32rpx;
					cursor: pointer;
				}

				.cancel-btn {
					color: #666;
					border-right: 1rpx solid #f5f5f5;
				}

				.confirm-btn {
					color: #4188EF;
				}
			}
		}
	}
</style>